<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/11/20
 * Time: 11:21
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

AppAsset::register($this);

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/skin/jedate.css');
AppAsset::addScript($this,$base . '/app/js/jedate.js');
AppAsset::addScript($this,$base . '/app/js/app-js.js');
AppAsset::addScript($this,$base . '/app/js/net-util.js');

//环信
AppAsset::addScript($this, $base . '/easemob/webim.config.js');
AppAsset::addScript($this, $base . '/easemob/strophe-1.2.8.min.js');
AppAsset::addScript($this, $base . '/easemob/websdk-1.4.11.js');


$model = new CommonHelper();

$tomorrowDate = $model->getTomorrowDateHI();
$yesterdayDate = $model->getYesterdayDateHI();

$baseRequestUrl = $model->getIp();
$easeAppKey = $model->getEaseAppKey();
$easeIdPre = $model->getEaseIdPre();
?>

<style>
    .webim-chatwindow-msg {
        z-index: 1;
        position: absolute;
        overflow-x: hidden;
        overflow-y: auto;
        box-sizing: border-box;
        padding: 20px 10px;
        width: 700px;
        height: 600px;
    }

    .message-row{
        margin-left: 1.7rem;
        margin-top: 20px;
    }
    .message-row span{
        color: #1a1a1a;
        font-size: 1.2rem;
    }

    .detail-div-get{
        background: #f1f2ec;
        border-radius: 6px;
        width: auto;
        height: auto;
        margin: 0 1.67rem;
        padding: 0.5rem 1.67rem;
        float: left;
    }
    .detail-div-put{
        background: #b4e4fc;
        border-radius: 6px;
        width: auto;
        height: auto;
        padding: 0.5rem 1.67rem;
        margin: 0 1.67rem;
        float: right;
    }

    .avatar{
        width: 3.3rem;
        height:3.3rem;
        float: left;
        border-radius: 1.65rem;
    }
    .nickname{
        color: #1a1a1a;
        font-size: 1.33rem;
    }
    .current-time{
        color: #1a1a1a;
        font-size: 1rem;
        margin-left: 1.5rem;
    }
    .message-detail {
        color: #1a1a1a;
        font-size: 1.17rem;
        margin-top: 0.5rem;
        overflow: hidden;
    }
    .gift{
        color: #A8A8A8;
        font-size: 1.17rem;
        width: 48rem;
    }
    .gift-img{
        float: right;
        width: 50px;
        height: 50px;
    }

    .user-item{
        padding-top: 8px;
        padding-bottom: 8px;
    }

    .user-name{
        width: 90px;
        height: 18px;
        display: inline-block;
        overflow: hidden;
    }

    .circle-red{
        width: 20px;
        height : 20px;
        background: #ff0000;
        color: white;
        border-radius: 50%;
        text-align: center;
        float: right;
    }

    .status-text{
        background: #E8E8EB;
        color: #999999;
        padding: 8px 10px;
        border-radius: 8px;
    }

    .user-avatar{
        width: 30px;
        height: 30px;
        margin-right: 5px;
        border-radius: 50%;
    }

    .dialog-operate{
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 200000;
        background-color: rgba(0,0,0,0.5);
    }

    .image-photo{
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        position: absolute;
    }
</style>
<div class="search-box">

    <div style="height: 715px; width: 200px; border-right:1px solid #ccc; float: left;">
        <div style="font-size: 15px; line-height: 50px; margin-left: 20px;color:#000;"><strong>对象</strong></div>
        <ul id="userChatList" style="font-size: 15px; margin-left: 20px;margin-right: 10px">
        </ul>
    </div>

    <div id="mainChatBox" style="float: left">
        <div style="height: 50px;line-height: 50px; font-size: 15px; width: 700px; float: left; border-bottom:1px solid #ccc;">
            <div style="float: left; color:#000; font-family:'微雅软黑'; margin-left: 20px;"><strong id="targetName"></strong><p id="chatType" style="color:red; font-size: 12px; font-family:'微雅软黑'; float: right; margin-left: 10px;"></p></div>
            <div style="float: right;">
                <span id="addFriend" href="" style="margin-right: 10px;" hidden="hidden">加为好友</span>
            </div>
        </div>
        <div style="clear: both"></div>
        <div id="wrappers" style="height: 600px;position: relative">
            <div id="wrapper123" class="webim-chatwindow-msg" hidden="hidden">

                <div class="message-row">

                    <img src="" class="avatar" style="float: right">

                    <div class="detail-div-put">
                        <div>
                            <span class="nickname">123123123</span>
                            <span class="current-time">123</span>
                        </div>
                        <span class="message-detail">哈哈哈</span>
                    </div>

                    <div style="clear: both"></div>
                </div>

                <div class="message-row">
                    <p style="text-align: center"><span class="status-text">好友添加申请</span></p>
                </div>

                <div class="message-row">

                    <img src="" class="avatar" style="float: right">

                    <div class="detail-div-put">
                        <div>
                            <span class="nickname">123123123</span>
                            <span class="current-time">123</span>
                        </div>
                        <span class="message-detail">哈哈哈</span>
                        <img class="gift-img" src="https://www.hoooty.com/user/images/skr.png" onclick="showPic('https://www.hoooty.com/user/images/skr.png')">
                    </div>

                    <div style="clear: both"></div>
                </div>

                <div class="message-row">

                    <img src="" class="avatar" style="float: left">

                    <div class="detail-div-get">
                        <div>
                            <span class="nickname">123123123</span>
                            <span class="current-time">123</span>
                        </div>
                        <span class="message-detail">哈哈哈</span>
                        <img class="gift-img" src="https://www.hoooty.com/user/images/skr.png">
                    </div>

                    <div style="clear: both"></div>
                </div>
            </div>
        </div>

        <div style="height: 65px; font-size: 15px; width: 700px; float: left; border:1px solid #ccc; border-right: none; border-left: none;">
            <div id="chatFooter" hidden="hidden">
                <input id="chatContent" type="text" style="border: 1px solid #ddd; border-radius: 6px; width: 360px; height: 38px; margin-top: 13px; margin-left: 20px;" maxlength="40" placeholder="请输入。。。">
                <button id="sendMessageButton" style="width: 57px; height: 32px; border-width: 0px; border-radius: 3px; background: #1E90FF; cursor: pointer; outline: none; font-family: Microsoft YaHei; color: white; font-size: 14px; margin-left: 20px;">发送</button>
            </div>

            <div id="noChatFooter" style="font-size: 14px; text-align: center;line-height: 65px" hidden="hidden">
                添加好友后才能聊天
            </div>
        </div>
    </div>
</div>

<div id="viewImage" class="dialog-operate" hidden="hidden" onclick="hidePic(this)">
    <img class="image-photo" src="" onload="setImage(this)">
</div>

<script>
    var baseApiHead = '<?= $baseRequestUrl?>';
    var appkey = '<?= $easeAppKey?>';
    var easeIdPre = '<?= $easeIdPre?>';
    var userId = '<?= $user['user_id']?>';
    var vestName = '<?= $user['user_nickname']?>';
    var vestAvatar = '<?= $user['user_avatar']?>';
    var vestCertificate = '<?= $user['is_certificate']?>';

    var token = '<?= $user['token']?>';
    var user = easeIdPre + userId.replace(/[^0-9]/ig,"");
    var pass="111111";

    var conn = new WebIM.connection({
        https: WebIM.config.https,
        url: WebIM.config.xmppURL,
        isAutoLogin: WebIM.config.isAutoLogin,
        isMultiLoginSessions: WebIM.config.isMultiLoginSessions
    });

    var options = {
        apiUrl: WebIM.config.apiURL,
        user: user,
        pwd: pass,
        appKey: appkey
    };

    $(document).ready(function() {

        if(targetId != -1){
            insertLeftLineData(easeIdPre + targetId,targetName,targetAvatar,targetVertification);

            $("#user"+easeIdPre + targetId).children('.circle-red').eq(0).text(0);
            $("#user"+easeIdPre + targetId).children('.circle-red').eq(0).hide();

            if($("#wrapper"+easeIdPre + targetId).length <= 0){
                $("#wrappers").append('<div id="wrapper'+easeIdPre + targetId+'" class="webim-chatwindow-msg"></div>');
            }

            $("#targetName").text(targetName);
            getUserRelationController.getUserRelationFunc(easeIdPre + targetId);
        }

        conn.open(options);
        conn.listen({
            onOpened: function ( message ) {},         //连接成功回调
            onClosed: function ( message ) {},         //连接关闭回调
            onTextMessage: function ( message ) {
                getMessageToHtml(message);
            },    //收到文本消息
            onEmojiMessage: function ( message ) {},   //收到表情消息
            onPictureMessage: function ( message ) {}, //收到图片消息
            onCmdMessage: function ( message ) {},     //收到命令消息
            onAudioMessage: function ( message ) {},   //收到音频消息
            onLocationMessage: function ( message ) {},//收到位置消息
            onFileMessage: function ( message ) {},    //收到文件消息
            onVideoMessage: function (message) {},     //收到视频消息
            onPresence: function ( message ) {},       //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
            onRoster: function ( message ) {},         //处理好友申请
            onInviteMessage: function ( message ) {},  //处理群组邀请
            onOnline: function () {
                window.location.reload();
            },                  //本机网络连接成功
            onOffline: function () {},                 //本机网络掉线
            onError: function ( message ) {
                try{
                    if(message.data.data.indexOf("user not found") > -1){
//                        RegisterEaseUser();
                    }
                }catch (e){

                }
            },          //失败回调
            onBlacklistUpdate: function (list) {}      //黑名单变动
        });

        $("#sendMessageButton").click(function(){
            var textContent = $("#chatContent").val();
            if(textContent.length < 1){
                alert("请输入内容");
                return;
            }

            if("3" == userRelationModel.status){
                userPartyChatController.userPartyChatFunc("1");
            }else{
                if("2" == userRelationModel.status && "1" == userRelationModel.chatStatus) {
                    if("2" == userRelationModel.userRole){
                        userRelationModel.chatStatus = "2";
                        updateReplyWordsController.updateReplyWordsFunc("1");
                    }else if("1" == userRelationModel.userRole){
                        if("0" == userRelationModel.sendOne){
                            userRelationModel.sendOne = "1";
                            updateReplyWordsController.updateReplyWordsFunc("2");
                        }
                    }
                }else
                    sendTextMessage(textContent,MESSAGE_TEXT_TYPE);
            }

        });

        $("#addFriend").click(function(){
            if(userRelationModel.userRole != null && "2" == userRelationModel.userRole) {
                addFriendController.addFriendFunc(targetId);
            }else{
                userPartyChatController.userPartyChatFunc("2");
            }
        })
    });

    function RegisterEaseUser(){

        $.ajax({
            type: "POST",
            url: "register-ease",
            data:{
                ease_id:user
            },
            success: function (result) {
                conn.open(options);
            }
        });
    }

    function insertLeftLineData(easeId,userName,userAvatar,userVertification){
        if($("#user"+easeId).length <= 0){
            $("#userChatList").prepend('<li id="user'+easeId+'" class="user-item" ease-id="'+easeId+'" user-name="'+userName+'" user-avatar="'+userAvatar+'" user-vertification="'+userVertification+'" onclick="goToChat(this)"><img class="user-avatar" src="'+userAvatar+'" alt=""><span class="user-name">'+userName+'</span><p class="circle-red">1</p></li>');
        }else{
            var messageCount = parseInt($("#user"+easeId).children('.circle-red').eq(0).text()) + 1;
            $("#user"+easeId).remove();
            $("#userChatList").prepend('<li id="user'+easeId+'" class="user-item" ease-id="'+easeId+'" user-name="'+userName+'" user-avatar="'+userAvatar+'" user-vertification="'+userVertification+'" onclick="goToChat(this)"><img class="user-avatar" src="'+userAvatar+'" alt=""><span class="user-name">'+userName+'</span><p class="circle-red">'+messageCount+'</p></li>');
        }
    }

    function getMessageToHtml(message){

        if(message.from == "admin" && message.ext.type != "ETM_GIFT" && message.ext.type != MESSAGE_ADDFRIEND_TYPE){
            return;
        }

        var dataHtml = "";

        var userAvatar = message.ext.user_avatar;
        var userName = message.ext.user_name;
        var userVertification = message.ext.is_vertification;

        insertLeftLineData(message.from,userName,userAvatar,userVertification);

        if($("#wrapper"+message.from).is(':visible')){

            $("#user"+message.from).children('.circle-red').eq(0).text(0);
            $("#user"+message.from).children('.circle-red').eq(0).hide();

            if("2" == userRelationModel.status && "1" == userRelationModel.chatStatus && "1" == userRelationModel.userRole) {
                getUserRelationController.getUserRelationFunc(message.from);
            }
        }

        switch (message.ext.type){
            case MESSAGE_TEXT_TYPE:
                var textContent = message.data;
                dataHtml = '<div class="message-row">'+
                '<img src="'+userAvatar+'" class="avatar">'+
                '<div class="detail-div-get">'+
                '<div>'+
                '<span class="nickname">'+userName+'</span>'+
                '<span class="current-time">'+getNowFormatDate()+'</span>'+
                '</div>'+
                '<span class="message-detail">'+textContent+'</span>'+
                '</div>'+
                '<div style="clear: both"></div>'+
                '</div>';
                break;

            case MESSAGE_OPENWHITE_TYPE:
                var openwhiteTitle = message.ext.openwhite_title;
                var partyContent = message.data;

                dataHtml = '<div class="message-row">'+
                '<img src="'+userAvatar+'" class="avatar">'+
                '<div class="detail-div-get">'+
                '<div>'+
                '<span class="nickname">'+userName+'</span>'+
                '<span class="current-time">'+getNowFormatDate()+'</span>'+
                '</div>'+
                '<p class="message-detail"><strong>'+openwhiteTitle+'</strong></p>'+
                '<span class="message-detail">'+partyContent+'</span>'+
                '</div>'+
                '<div style="clear: both"></div>'+
                '</div>';
                break;

            case MESSAGE_GIFT_TYPE:
                var giftContent = "送了"+message.ext.gift_name;
                var giftPic = message.ext.gift_pic;
                dataHtml = '<div class="message-row">'+
                '<img src="'+userAvatar+'" class="avatar">'+
                '<div class="detail-div-get">'+
                '<div>'+
                '<span class="nickname">'+userName+'</span>'+
                '<span class="current-time">'+getNowFormatDate()+'</span>'+
                '</div>'+
                '<span class="message-detail">'+giftContent+'</span>'+
                '<img class="gift-img" src="'+giftPic+'">'+
                '</div>'+
                '<div style="clear: both"></div>'+
                '</div>';
                break;

            case MESSAGE_IMAGE_TYPE:
                var imageUrl = message.ext.pic;
                dataHtml = '<div class="message-row">'+
                '<img src="'+userAvatar+'" class="avatar">'+
                '<div class="detail-div-get">'+
                '<div>'+
                '<span class="nickname">'+userName+'</span>'+
                '<span class="current-time">'+getNowFormatDate()+'</span>'+
                '</div>'+
                '<span class="message-detail">[图片]</span>'+
                '<img class="gift-img" src="'+imageUrl+'" onclick="showPic(this)">'+
                '</div>'+
                '<div style="clear: both"></div>'+
                '</div>';
                break;

            case MESSAGE_ADDFRIENDDONE_TYPE:
                var addFriendContent = message.data;
                if(message.data != "双方已互为好友，开启无限畅聊"){
                    addFriendContent = "对方已加你为好友";
                    $("#addFriend").hide();
                } else{
                    $("#chatFooter").show();
                    $("#chatContent").attr('placeholder',"请输入。。。");
                    $("#noChatFooter").hide();

                    $("#chatType").text("聊天");
                    $("#addFriend").hide();
                    if(timeInterval)
                        clearInterval(timeInterval);

                    userRelationModel.status = "1";
                }

                dataHtml = '<div class="message-row">'+
                '<p style="text-align: center"><span class="status-text">'+addFriendContent+'</span></p>'+
                '</div>';
                break;

            default :
                break;
        }

        if($("#wrapper"+message.from).length <= 0){
            $("#wrappers").append('<div id="wrapper'+message.from+'" class="webim-chatwindow-msg" hidden="hidden"></div>');
        }

        $("#wrapper"+message.from).append(dataHtml);
    }

    function sendMessageToHtml(content,type){

        var dataHtml = "";

        switch (type){
            case MESSAGE_TEXT_TYPE:
                dataHtml = '<div class="message-row">'+
                '<img src="'+vestAvatar+'" class="avatar" style="float: right">'+
                '<div class="detail-div-put">'+
                '<div>'+
                '<span class="nickname">'+vestName+'</span>'+
                '<span class="current-time">'+getNowFormatDate()+'</span>'+
                '</div>'+
                '<span class="message-detail">'+content+'</span>'+
                '</div>'+
                '<div style="clear: both"></div>'+
                '</div>';
                break;

            case MESSAGE_OPENWHITE_TYPE:
                var openwhiteTitle = partyTheme;

                dataHtml = '<div class="message-row">'+
                '<img src="'+vestAvatar+'" class="avatar" style="float: right">'+
                '<div class="detail-div-put">'+
                '<div>'+
                '<span class="nickname">'+vestName+'</span>'+
                '<span class="current-time">'+getNowFormatDate()+'</span>'+
                '</div>'+
                '<p class="message-detail"><strong>'+openwhiteTitle+'</strong></p>'+
                '<span class="message-detail">'+content+'</span>'+
                '</div>'+
                '<div style="clear: both"></div>'+
                '</div>';
                break;

            case MESSAGE_ADDFRIENDDONE_TYPE:
                var addFriendContent = content;
                if(addFriendContent != "双方已互为好友，开启无限畅聊")
                    addFriendContent = "你已加为好友";
                else{
                    $("#chatFooter").show();
                    $("#chatContent").attr('placeholder',"请输入。。。");
                    $("#noChatFooter").hide();

                    $("#chatType").text("聊天");
                    $("#addFriend").hide();
                    if(timeInterval)
                        clearInterval(timeInterval);

                    userRelationModel.status = "1";
                }

                dataHtml = '<div class="message-row">'+
                '<p style="text-align: center"><span class="status-text">'+addFriendContent+'</span></p>'+
                '</div>';
                break;

            default :
                break;
        }

        if($("#wrapper"+easeIdPre+targetId).length <= 0){
            $("#wrappers").append('<div id="wrapper'+easeIdPre+targetId+'" class="webim-chatwindow-msg"></div>');
        }

        $("#wrapper"+easeIdPre+targetId).append(dataHtml);
    }
    //获取当前时间Y-m-d H:i:s
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + hours + seperator2 + minutes + seperator2 + seconds;
        return currentdate;
    }

    function goToChat(view){
        $(".webim-chatwindow-msg").hide();

        var ease_id = $(view).attr("ease-id");
        $("#user"+ease_id).children('.circle-red').eq(0).text(0);
        $("#user"+ease_id).children('.circle-red').eq(0).hide();

        targetId = ease_id.replace(easeIdPre,"");
        targetName = $(view).attr("user-name");
        targetAvatar = $(view).attr("user-avatar");
        targetVertification = $(view).attr("user-vertification");

        $("#targetName").text(targetName);

        $("#chatType").text("");
        $("#addFriend").hide();
        if(timeInterval)
            clearInterval(timeInterval);

        getUserRelationController.getUserRelationFunc(ease_id);
    }

    var MESSAGE_TEXT_TYPE = "text";//开场白
    var MESSAGE_OPENWHITE_TYPE = "openwhite";//纯文字
    var MESSAGE_ADDFRIEND_TYPE = "addFriend";//提醒加好友
    var MESSAGE_ADDFRIENDDONE_TYPE = "addFriendDone";//对方已加你为好友
    var MESSAGE_GIFT_TYPE = "gift";//礼物
    var MESSAGE_IMAGE_TYPE = "image";//图片
    var userRelationModel;

    var targetId = '<?= isset($target_user['user_id'])?$target_user['user_id']:-1?>';
    var targetName = '<?= isset($target_user['user_id'])?$target_user['user_nickname']:-1?>';
    var targetAvatar = '<?= isset($target_user['user_id'])?$target_user['user_avatar']:-1?>';
    var targetVertification = '<?= isset($target_user['user_id'])?$target_user['is_certificate']:-1?>';

    var partyTheme = "";
    var userPartyChatController = {
        userPartyChatApi:baseApiHead + "Hotcity/v1/userparties",
        userPartyChatFunc:function(type){
            var param = {
                user_id:userId,
                token:token,
                tid:targetId,
                type:type
            };

            sendAjax(this.userPartyChatApi,"POST",param,false,function(res){
                if(res.code != 0){
                    if("2" == type){
                        addFriendController.addFriendFunc(targetId);
                    }else if("1" == type){

                        partyTheme = userRelationModel.party_theme;
                        sendTextMessage($("#chatContent").val(),MESSAGE_OPENWHITE_TYPE);
                        getUserRelationController.getUserRelationFunc(easeIdPre+targetId);
                    }
                }else{
                    alert(res.msg);
                }
            });
        }
    };

    var updateReplyWordsController = {
        updateReplyWordsApi:baseApiHead + "Hotcity/v1/userparties",
        updateReplyWordsFunc : function(type){
            var param = {
                user_id : userId,
                token : token,
                userparty_id : userRelationModel.userparty_id,
                type:type
            };

            sendAjax(this.updateReplyWordsApi,"PUT",param,false,function(res){
                if(res.code != 0){
                    sendTextMessage($("#chatContent").val(),MESSAGE_TEXT_TYPE);

                    if("2" == type){
                        $("#chatFooter").hide();
                        $("#noChatFooter").text("对方回复后，开始聊天");
                        $("#noChatFooter").show();
                    }
                }else{
                    alert(res.msg);
                }
            });
        }
    };

    var addFriendController = {
        addFriendApi:baseApiHead + "Hotcity/v1/friends",
        addFriendFunc : function(targetUserId){
            var param = {
                user_id : userId,
                token:token,
                target_user_id:targetUserId,
                type : "1"
            };

            sendAjax(this.addFriendApi,"POST",param,false,function(res){
                if(res.code != 0){
                    if("2" == userRelationModel.status){
                        $("#addFriend").hide();
                        if(userRelationModel.friendStatus != null){

                            if("2" == userRelationModel.friendStatus){
                                sendTextMessage("你已加TA为好友",MESSAGE_ADDFRIENDDONE_TYPE);
                                userRelationModel.friendStatus = "3";
                            }else if("4" == userRelationModel.friendStatus){
                                sendTextMessage("双方已互为好友，开启无限畅聊",MESSAGE_ADDFRIENDDONE_TYPE);
                                $("#chatType").text("聊天");
                                $("#chatFooter").show();
                                $("#chatContent").attr('placeholder',"请输入。。。");
                                $("#noChatFooter").hide();
                            }else{
                                alert("你已添加对方为好友");
                            }
                        }else{
                            sendTextMessage("你已加TA为好友",MESSAGE_ADDFRIENDDONE_TYPE);
                            userRelationModel.friendStatus = "3";
                        }
                    }else if("4" == userRelationModel.status){
                        if(userRelationModel.userRole != null && userRelationModel.userRole == "2"){
                            sendTextMessage("双方已互为好友，开启无限畅聊",MESSAGE_ADDFRIENDDONE_TYPE);
                            $("#chatType").text("聊天");
                            $("#chatFooter").show();
                            $("#chatContent").attr('placeholder',"请输入。。。");
                            $("#noChatFooter").hide();
                        }else{
                            sendTextMessage(vestName + " 向你打了一个招呼",MESSAGE_TEXT_TYPE);
                            sendTextMessage("你已加TA为好友",MESSAGE_ADDFRIENDDONE_TYPE);
                            userRelationModel.friendStatus = "3";
                        }
                    }else{
                        sendTextMessage("你已加TA为好友",MESSAGE_ADDFRIENDDONE_TYPE);
                        userRelationModel.friendStatus = "3";
                    }
                }else{
                    alert(res.msg);
                }
            });
        }
    };

    var sendTextMessage = function (content , type) {
        var id = conn.getUniqueId();                 // 生成本地消息id
        var msg = new WebIM.message('txt', id);      // 创建文本消息
        msg.set({
            msg: content,                  // 消息内容
            to: easeIdPre+targetId,                          // 接收消息对象（用户id）
            roomType: false,
            ext:commonExt(content , type),
            success: function (id, serverMsgId) {
                $("#chatContent").val("");
                sendMessageToHtml(content,type);
            },
            fail: function(e){
                console.log("Send private text error");
            }
        });
        msg.body.chatType = 'singleChat';
        conn.send(msg.body);
    };

    function commonExt(content,type){
        var ext = {
            type : type,
            user_name:vestName,
            user_avatar:vestAvatar,
            is_vertification:vestCertificate,
            other_user_name:targetName,
            other_user_avatar:targetAvatar,
            other_is_vertification:targetVertification
        };
        if("2" == userRelationModel.status && "双方已互为好友，开启无限畅聊" != content){
            var endDate = new Date(userRelationModel.createTime);
            var end = endDate.getTime();
            ext.party_time_stamp = (end/1000).toString();
        }

        switch (type){
            case MESSAGE_OPENWHITE_TYPE:
                ext.openwhite_title = partyTheme;
                if("双方已互为好友，开启无限畅聊" != content){
                    var date = new Date();
                    var endStamp = date.getTime();
                    ext.party_time_stamp = (endStamp/1000).toString();
                }
                break;
        }

        return ext;
    }

    var getUserRelationController = {
        getUserRelationApi : baseApiHead + "Hotcity/v1/friends",
        getUserRelationFunc : function(ease_id){
            var targetUserId = ease_id.replace(easeIdPre,"");
            var param = {
                user_id: userId,
                token:token,
                target_user_id:targetUserId
            };

            sendAjax(this.getUserRelationApi,"GET",param,false,function(res){
               if(res.code != 0){
                   $("#wrapper"+ease_id).show();

                   var result = JSON.parse(res);
                   userRelationModel = result.data;
                   initViewByUserRelation();
                   initRightAddButton();
               }else{
                   alert(res.msg);
               }
            });
        }
    };

    function initRightAddButton(){
        if("1" == userRelationModel.status) {
            $("#addFriend").hide();
        }else if("2" == userRelationModel.status){

            if("3" != userRelationModel.friendStatus) {
                $("#addFriend").show();
            }else{
                $("#addFriend").hide();
            }
        }else if("4" == userRelationModel.status){
            if("3" == userRelationModel.chatStatus){
                if("2" == userRelationModel.userRole){
                    $("#addFriend").show();
                    $("#noChatFooter").text("对方向你打了个招呼");
                }else{
                    $("#addFriend").hide();
                }
            }
        }
    }

    function initViewByUserRelation(){
        switch (userRelationModel.status){
            case 1:
                $("#chatType").text("聊天");
                $("#chatFooter").show();
                $("#chatContent").attr('placeholder',"请输入。。。");
                $("#noChatFooter").hide();
                break;

            case 2:
                if("1" == userRelationModel.userRole) {
                    if("2" == userRelationModel.chatStatus){
                        $("#chatFooter").show();
                        $("#chatContent").attr('placeholder',"请输入。。。");
                        $("#noChatFooter").hide();
                    }else {
                        if ("1" == userRelationModel.sendOne) {
                            $("#chatFooter").hide();
                            $("#noChatFooter").text("对方回复后，开始聊天");
                            $("#noChatFooter").show();
                        } else {
                            $("#chatFooter").show();
                            $("#chatContent").attr('placeholder',"对方回复前,还可发送一条");
                            $("#noChatFooter").hide();
                        }
                    }
                }else{
                    $("#chatFooter").show();
                    $("#chatContent").attr('placeholder',"请输入。。。");
                    $("#noChatFooter").hide();
                }

                //获取当前时间
                var date = new Date();
                var timeStamp = date.getTime();
                var timeRest = 0;

                var endDate = new Date(userRelationModel.createTime);
                var end = endDate.getTime();

                timeRest = timeStamp/1000 - end/1000;
                timeRest = 86400 - timeRest;

                if(timeRest <= 0){
                    $("#chatFooter").hide();
                    $("#noChatFooter").text("24小时中未互加好友，派对结束");
                    $("#noChatFooter").show();
                }else{
                    endTimeStamp = end + 86400000;
                    countTime();

                    timeInterval = setInterval(function(){
                        countTime();
                    },1000);
                }

                $("#addFriend").show();
                break;

            case 3:
                $("#chatType").text("对方派对主题["+userRelationModel.party_theme+"]");
                $("#chatFooter").show();
                $("#chatContent").attr('placeholder',"发送开场白");
                $("#noChatFooter").hide();

                $("#addFriend").show();
                break;

            case 4:
                $("#chatType").text("聊天");
                $("#chatFooter").hide();
                $("#noChatFooter").text("加为好友后，开始聊天");
                $("#noChatFooter").show();

                $("#addFriend").show();
                break;
        }
    }

    var endTimeStamp;
    var timeInterval;

    function countTime() {
        //获取当前时间
        var date = new Date();
        var now = date.getTime();

        //时间差
        var leftTime = endTimeStamp-now;
        //定义变量 d,h,m,s保存倒计时的时间
        var d,h,m,s;
        if (leftTime>=0) {
            d = Math.floor(leftTime/1000/60/60/24);
            h = Math.floor(leftTime/1000/60/60%24);
            m = Math.floor(leftTime/1000/60%60);
            s = Math.floor(leftTime/1000%60);
        }
        //将0-9的数字前面加上0，例1变为01
        d = checkTime(d);
        h = checkTime(h);
        m = checkTime(m);
        s = checkTime(s);
        function checkTime(i){
            if (i<10) {
                i = "0"+i;
            }
            return i;
        }
        //将倒计时赋值到div中
        $("#chatType").text(h+":"+m+":"+s);
    }

    function showPic(view){
        $(".image-photo").attr("src",$(view).attr("src"));
        $("#viewImage").show();
    }

    function hidePic(view){
        $(".image-photo").attr("src","");
        $(view).hide();
    }

    function setImage(e){
        if(e.naturalWidth/e.naturalHeight>=1){
            //$('#techCube').removeClass('hLit');
            $(e).css({width:600,height:'auto'});
        }else{
            //$('#techCube').addClass('hLit');
            $(e).css({height:600,width:'auto'});
        }
    }
</script>